package com.lxl.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 北上寻海
 */
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        /**
         * 目前所有路径都拦截了
         * 以下路径是不能拦截的
         *     index.jsp(登录页面)
         *     /welcome(判断是否有七天免登录的cookie页面)
         *     已经登录了，在session域中存了登录信息了
         */
        String servletPath = request.getServletPath();
        //拿当前的session：默认是true，表示如果没有就新建一个；false是没有就返回null
        HttpSession session = request.getSession(false);
        String indexPage = "/index.jsp";
        String welcomePage ="/welcome";
        String loginPage = "/login";
        String verifyCodePage ="/verifyCode";
        boolean result = indexPage.equals(servletPath)||welcomePage.equals(servletPath)||loginPage.equals(servletPath)
                ||verifyCodePage.equals(servletPath)||session.getAttribute("user")!=null;

        if(result){
            chain.doFilter(request, response);
        }
        else {
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
